package com.efo.common.utils;

import com.github.pagehelper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @Package: com.efo.common.utils
 * @Description: IP工具类
 * @Author CHY
 * @Create 2021年11月08日 15时22分09秒
 */
public class IPUtils {
    /**
     * @Author: CHY
     * @Date: 2021年11月08日 03时22分56秒
     * @Description: 获取ip地址
     * @param request
     * @return java.lang.String
     **/
    public static String getIp(HttpServletRequest request) {
        if (request == null)
            return "";
        String ip = request.getHeader("X-Requested-For");
        if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            return "127.0.0.1";
        }
        return ip;
    }

    /**
     * @Author: CHY
     * @Date: 2021年11月08日 03时22分32秒
     * @Description: 判断是否本机
     * @param ip
     * @return boolean
     **/
    public static boolean isLocalHost(String ip) {
        return "127.0.0.1".equals(ip) || "localhost".equals(ip);
    }
}
